package com.study.netProtocol.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author ysy
 * @version 1.0
 * @Title: UdpClient
 * @Note <b>ProjectName:</b> Pre-research
 * <br><b>PackageName:</b> com.study.netProtocol.udp
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>

 */
public class UdpClient {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        ds.setSoTimeout(1000);
        // 连接指定服务器和端口
        ds.connect(InetAddress.getByName("localhost"), 6666);
        // 发送:
        byte[] data = "Hello".getBytes();
        System.out.println("发送消息：");
        DatagramPacket packet = new DatagramPacket(data, data.length);
        ds.send(packet);
        // 接收服务端返回信息:
        byte[] buffer = new byte[1024];
        packet = new DatagramPacket(buffer, buffer.length);
        ds.receive(packet);
        String resp = new String(packet.getData(), packet.getOffset(), packet.getLength());
        System.out.println("接收到返回：" + resp);
        ds.disconnect();

    }
}
